<template>
    <el-form label-width="100">
        <el-form-item label="SPU名称">
            <el-input placeholder="请您输入SPU名称" v-model="spuParams.spuName"></el-input>
        </el-form-item>
        <el-form-item label="SPU品牌">
            <el-select placeholder="请您选择品牌" style="width: 250px;" v-model="spuParams.tmId">
                <el-option v-for="(trademark, index) in allTradeMark" :key="trademark.id" :label="trademark.tmName"
                    :value="trademark.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" placeholder="请您输入描述" v-model="spuParams.description"></el-input>
        </el-form-item>
        <el-form-item label="SPU图片">
            <el-upload :limit="10" :on-exceed="exceedHandler" :before-upload="beforeHandler" :on-preview="prviewHandler"
                v-model:file-list="spuImgArr" action="/app-dev/admin/product/fileUpload" list-type="picture-card">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisibe" align-center>
                <div class="dialog">
                    <img :src="imgUrl" style="width: 300px;height: 300px;" />
                </div>
            </el-dialog>
        </el-form-item>
        <el-form-item label="SPU销售属性">
            <!--下拉菜单展示还未选择的销售属性:收集属性的ID与属性名字-->
            <el-select v-model="unSaleAttrIdAndName" :placeholder="showText" style="width: 240px;margin-right: 10px;">
                <el-option v-for="(item, index) in unSaleAttr" :key="item.id" :label="item.name"
                    :value="`${item.id}:${item.name}`"></el-option>
            </el-select>

            <el-button @click="addSaleAttr" :icon="Plus" type="primary"
                :disabled="!!!unSaleAttrIdAndName">添加销售属性</el-button>
            <el-table border style="margin: 10px 0px;" :data="spuSaleAttr">
                <el-table-column type="index" align="center" width="80" label="序号"></el-table-column>
                <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
                <el-table-column label="属性值">
                    <!-- row:即为每一个已有的属性对象 -->
                    <template #="{ row, $index }">
                        <!-- 展示已有的属性值 -->
                        <el-tag @close="row.spuSaleAttrValueList.splice(index, 1)" style="margin:0px 5px" closable
                            v-for="(item, index) in row.spuSaleAttrValueList" :key="item.id">{{ item.saleAttrValueName
                            }}</el-tag>
                        <!--编辑模式input  -->
                        <el-input v-model="row.inputVal" @blur="toLook(row)" v-if="row.showInput" style="width: 100px;"
                            placeholder="请你输入属性值" size="small"></el-input>
                        <!-- 查看模式下的button -->
                        <el-button :icon="Plus" type="primary" size="small" v-else @click="toEdit(row)"></el-button>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #="{ row, $index }">
                        <el-button @click="spuSaleAttr.splice($index, 1)" size="small" type="danger"
                            :icon="Delete"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="save" :disabled="spuSaleAttr.length > 0 ? false : true">保存</el-button>
            <el-button @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { Plus, Delete } from '@element-plus/icons-vue'
import { reqAllTradeMark, reqSpuImageList, reqAllSale, reqSaleAttrList,reqAddOrUpdateSpu } from '@/api/product/spu';
import { ref, reactive, computed,nextTick } from 'vue';
import { ElMessage } from 'element-plus';
//全部品牌
const allTradeMark = ref<any>([]);
//已有的销售属性
const spuSaleAttr = ref<any>([]);
//全部销售属性
const allSaleAttr = ref<any>([]);
//收集还未拥有的销售属性ID与属性名字
const unSaleAttrIdAndName = ref<string>('')
// 储存已有SPU
const spuParams = reactive<any>({});
//SPU照片墙
const spuImgArr = ref<any>([]);
// 控制照片墙的放大预览，显示与隐藏
const dialogVisibe = ref<boolean>(false);
//存储预览图片地址
const imgUrl = ref<any>(false);
//取消按钮的回调
const cancel = () => {
    $emit('changeScene', 0);
}
//当前子组件的一个方法--用于初始化完成的SPU
const initHasSpu = async (spu: any) => {
    //存储已有的SPU
    Object.assign(spuParams, spu);
    //获取全部的品牌数据
    const result1 = await reqAllTradeMark();
    allTradeMark.value = result1;
    //获取已有的SPU照片墙的数据
    const result2 = await reqSpuImageList(spu.id);
    spuImgArr.value = result2.map((item: any) => {
        return {
            name: item.imgName,
            url: item.imgUrl
        }
    });
    //获取当前已有的SPU已有的销售属性
    const result3 = await reqSaleAttrList(spu.id);
    spuSaleAttr.value = result3;
    console.log(result3);
    //获取全部销售属性
    const result4 = await reqAllSale();
    allSaleAttr.value = result4;
}
//计算出当前已有的SPU还未拥有的销售属性
const unSaleAttr = computed(() => {
    //全部销售属性进行过滤
    return allSaleAttr.value.filter((item: any) => {
        //过滤的条件需要布尔值:true->当前元素item作为新的数组的元素
        return spuSaleAttr.value.every((hasSale: any) => {
            return item.name != hasSale.saleAttrName;
        })
    })
})
const showText = computed(() => {
    return unSaleAttr.value.length == 0 ? '未能选择' : `还有${unSaleAttr.value.length}个销售属性未选择`
})
// 添加销售属性
const addSaleAttr = () => {
    //解构出收集到的还未拥有的销售属性的ID与名字
    const [baseSaleAttrId, saleAttrName] = unSaleAttrIdAndName.value.split(':');
    const newSaleAttr = {
        baseSaleAttrId, //销售属性的ID
        saleAttrName,//销售属性的名字
        spuSaleAttrValueList: []
    }
    //追加到已有的销售属性的数组当中
    spuSaleAttr.value.push(newSaleAttr);
    //清空收集到的数据
    unSaleAttrIdAndName.value = '';
    
//   // 获取表单元素聚焦
//   nextTick(() => {
//     inputElement.value.focus();
//   })
}
//照片墙预览的钩子 
const prviewHandler = (file: any) => {
    //展示对话框
    dialogVisibe.value = true;
    //存储图片地址
    imgUrl.value = file.url;
}
//照片墙上传之前钩子:约束大小与约束文件类型
const beforeHandler = (file: any) => {
    if (file.type === 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') {
        if (file.size / 1024 / 1024 < 2) {
            return true;
        } else {
            ElMessage({
                type: 'error',
                message: '文件大小不能超出2M'
            })
            return false;
        }
    } else {
        ElMessage({
            type: 'error',
            message: '文件格式不正确'
        })
        return false;
    }
}
//上传文件数量钩子
const exceedHandler = () => {
    ElMessage({
        type: 'error',
        message: '文件数量最多10'
    })
}

//属性值按钮回调-编辑模式
const toEdit = (row: any) => {
    row.showInput = true;
}

//表单元素失却焦点事件
const toLook = (row: any) => {

    //非法情况判断
    if (row.inputVal.trim() == '') {
        ElMessage({
            type: 'error',
            message: '属性值不能重复'
        })
        return;
    }
    //属性值不能重复
    const repeat = row.spuSaleAttrValueList.find((item: any) => {
        return item.saleAttrValueName == row.inputVal;
    })

    if (repeat) {
        ElMessage({
            type: 'error',
            message: '属性值不能重复'
        })
        return;
    }
    //收集新增的属性值对象
    const newSaleAttrValue = {
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.inputVal
    }
    //收集新增的属性值
    row.spuSaleAttrValueList.push(newSaleAttrValue);
    //清空数据
    row.inputVal = '';
    //变为查看模式
    row.showInput = false;
}
//保存按钮回调
const save = async () => {
    //整理参数:照片墙与销售属性
    spuParams.spuImageList = spuImgArr.value.map((item: any) => {
        return {
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url
        }
    })
    spuParams.spuSaleAttrList = spuSaleAttr.value;
    //发请求:成功、失败
    try {
        //更新或者添加SPU成功
        await reqAddOrUpdateSpu(spuParams);
        ElMessage({
            type: 'success',
            message: `${spuParams.id ? '更新成功' : '添加成功'}`
        })
        //通知父组件切换场景为0
        $emit('changeScene', 0);

    } catch (error) {
        ElMessage({
            type: 'error',
            message: `${spuParams.id ? '更新失败' : '添加失败'}`
        })
    }
    //请求成功:通知父组件切换场景,再次获取最新的SPU数据
}
//自定义事件
const $emit = defineEmits(['changeScene']);
//对外暴露
defineExpose({
    initHasSpu
})
</script>

<style scoped>
.dialog {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>